import React, { useEffect, useState } from 'react';
import { Col, Icon, List, Row, Input, InputNumber, message, Form } from 'antd';
import AxCard from '@/components/AxBase/AxCard';
import './style.css';
import { AxButton } from '@/components/AxBase';
import { AxTable } from '@/components/AxList';
import { axconst } from '@/shared/axconst';
import { axhttp, databasePrefix } from '@/utils/axhttp';
import AxColumnAction from '@/components/AxList/AxColumnAction';
import { router } from 'umi';
import { axdatehelper, axhelper } from '@/shared/axhelper';
import { AxInput, AxPlaceHolder, AxSelectEnum, AxTextArea } from '@/components/AxForm/AxFormItem';
import { AxUploadPicture } from '@/components/AxForm/AxFormItem/AxUpload';

const { getXhr, postFormXhr } = axhttp;
const { Search } = Input;
const Index: React.FC<any> = props => {
  const { form } = props;
  const [data, setData] = useState<any>({});
  const [loading, setLoading] = useState(false);
  const [submiting, setSubmiting] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState<any>([]);
  const [sumPrice, setSumPrice] = useState<any>(0);
  const [searchParams, setSearchParams] = useState<any>({});
  const user = axhelper.getUserInfo();
  useEffect(() => {
    handleReadGoods();
  }, []);

  /** 获取商品列表 */
  const handleReadGoods = (p: any = {}) => {
    setLoading(true);
    setSubmiting(true);

    return getXhr('/api/cart/read', {
      ...searchParams,
      ...p,
    })
      .then((res: any) => {
        setData(res);
        return Promise.resolve(res);
      })
      .finally(() => {
        setLoading(false);
        setSubmiting(false);
      });
  };

  const columns = [
    {
      dataIndex: 'image',
      width: 110,
      render: (val: any) => {
        return (
          <img
            src={(val && val !== '' && val) || '/img/nopic.jpg'}
            style={{ height: 110, width: 110 }}
          />
        );
      },
    },
    {
      width: axconst.width.longx,
      render: (val: any, record: any) => {
        return (
          <div style={{ marginLeft: 16 }}>
            <h4 className="ant-list-item-meta-title">{record.name}</h4>
            {/* <div className="ant-list-item-meta-description">{record.eName}</div> */}
          </div>
        );
      },
    },
    {
      width: axconst.width.long,
      render: (val: any, record: any) => {
        return (
          <div>
            <div>
              <span>产品规格：{record.productSpec}</span>
            </div>
            <div>
              <span>别名：{record.alias}</span>
            </div>
          </div>
        );
      },
    },
    {
      width: axconst.width.long,
      render: (val: any, record: any) => {
        return (
          <div>
            <div>
              <span>单价：￥{record.price}</span>
            </div>
            <div>
              <span>库存：{record.stock}</span>
            </div>
            {/* <div>
              <span>管控：{record.controlLevel}</span>
            </div> */}
          </div>
        );
      },
    },
    {
      width: axconst.width.long,
      render: (val: any, record: any) => {
        return (
          <div>
            {/* <div>
              <span>包装：{record.packingUnit}</span>
            </div> */}
            {/* <div>
              <span>性状：{record.character}</span>
            </div> */}
            <div>
              <span>销量：{record.saleAmount}</span>
            </div>
            <div>
              <span>品类名称：{record.categoryName}</span>
            </div>
          </div>
        );
      },
    },
    {
      dataIndex: 'amount',
      width: 130,
      render: (val: any, record: any) => (
        <div onClick={e => e.stopPropagation()}>
          <InputNumber
            style={{ width: 120 }}
            defaultValue={val}
            min={1}
            onBlur={e => handleBlur(e, record)}
          />
        </div>
      ),
    },
    {
      width: 130,
      render: (val: any, record: any) => (
        <div onClick={e => e.stopPropagation()}>
          <AxColumnAction
            buttons={[
              {
                text: '删除',
                popconfirm: true,
                group: false,
                onClick: () => handleDelete(record.id),
              },
            ]}
          />
        </div>
      ),
    },
  ];

  /** 选中处理函数 */
  const handleSelectRow = (selectedRows: any) => {
    setSelectedProduct(selectedRows);
    handleCalculate(selectedRows);
  };

  /** 修改购买量 */
  const handleBlur = (e: any, r: any) => {
    setSubmiting(true);
    return postFormXhr('/api/cart/update', {
      id: r.id,
      amount: e.target.value,
    })
      .then(() => {
        handleReadGoods()
          .then(() => {
            handleCalculate(selectedProduct);
          })
          .finally(() => {
            setSubmiting(false);
          });
      })
      .catch(() => {
        setSubmiting(false);
      });
  };

  /** 删除商品 */
  const handleDelete = (id: any) => {
    setSubmiting(true);
    return postFormXhr('/api/cart/destroy', {
      id,
    })
      .then(() => {
        message.success('删除成功');
        const idx = selectedProduct.findIndex((i: any) => i.id === id);
        selectedProduct.splice(idx, 1);
        handleReadGoods()
          .then(() => {
            handleCalculate(selectedProduct);
          })
          .finally(() => {
            setSubmiting(false);
          });
      })
      .catch(() => {
        setSubmiting(false);
      });
  };

  /** 计算总价
   * @param s 选中的商品
   */
  const handleCalculate = (s: any) => {
    let sum = 0;
    data.list.forEach((j: any) => {
      const f = s.find((m: any) => m.productId === j.productId);
      if (f) {
        sum = sum + j.price * j.amount;
      }
    });

    setSumPrice(axhelper.toFixed(sum));
  };

  /** 提交商品 */
  const handleSubmit = () => {
    form.validateFields((err: any, fieldsValue: any) => {
      if (err) return;

      if (!selectedProduct || selectedProduct.length == 0) {
        message.warning('请至少选中一件商品！');
        return;
      }

      const orderNo = axhelper.guid();
      const user = axhelper.getUserInfo();
      postFormXhr('/api/order/create', {
        orderNo: orderNo,
        payment: sumPrice,
        paymentType: fieldsValue.paymentType,
        postage: 0,
        receiver: fieldsValue.receiver,
        mobile: fieldsValue.mobile,
        address: fieldsValue.address,
        person: user.name,
        userId: user.id,
        createTime: axdatehelper.Dateformat(new Date(), 'yyyy-MM-dd HH:mm:ss'),
        orderStatus: 2
      }).then(async () => {
        const create = async (i: any) => {
          await postFormXhr('/api/orderGoods/create', {
            ...i,
            receiver: fieldsValue.receiver,
            mobile: fieldsValue.mobile,
            orderNo: orderNo,
          });
        };
        const destroy = async (id: any) => {
          await postFormXhr('/api/cart/destroy', {
            id,
          });
        };
        for (let i = 0; i < selectedProduct.length; i++) {
          const p = { ...selectedProduct[i] };
          await create(p);
        }
        message.success('提交成功');
        for (let i = 0; i < selectedProduct.length; i++) {
          await destroy(selectedProduct[i].id);
        }
        router.push({ pathname: '/buyer/material/order/nocommit' });
      });
    });
  };

  /** 搜索商品 */
  const handleSearch = (v: any) => {
    const p = { name: v };
    setSearchParams(p);
    handleReadGoods(p);
  };

  return (
    <>
      <div style={{ borderBottom: '2px solid #409eff' }}>
        <AxCard
          style={{ marginBottom: '15px', height: '100%', width: 1390, margin: '24px auto' }}
          bodyStyle={{ padding: 0 }}
        >
          <Row>
            <Col span={18}>
              <div style={{ fontSize: 22 }}>
                <Icon type="shopping-cart" />
                &nbsp;我的购物车
              </div>
            </Col>
            <Col span={6}>
              <Search placeholder="请输入商品名称搜索" onSearch={handleSearch} allowClear />
            </Col>
          </Row>
        </AxCard>
      </div>
      <AxCard
        style={{ height: '100%', width: 1390, margin: '0 auto' }}
        bodyStyle={{ paddingLeft: 0, paddingRight: 0 }}
      >
        <AxTable
          size="default"
          bordered={false}
          showPagination={false}
          loading={loading}
          columns={columns}
          data={data}
          onSelectRow={(selectedRows: any) => handleSelectRow(selectedRows)}
        />
      </AxCard>
      <AxCard
        style={{ height: '100%', width: 1390, margin: '0 auto' }}
        bodyStyle={{ paddingLeft: 0, paddingRight: 0 }}
      >
        <List
          size="small"
          rowKey={(r: any) => r.id}
          dataSource={[{ id: 'ax-00001' }]}
          renderItem={() => (
            <List.Item style={{ fontWeight: 'bold' }}>
              <Col span={7}>
                <span>合计</span>
              </Col>
              <Col span={3}></Col>
              <Col span={3}></Col>
              <Col span={3}></Col>
              <Col span={2}>
                已选择<span style={{ color: 'rgb(229, 67, 70)' }}>{selectedProduct.length}</span>
                件商品
              </Col>
              <Col span={2}>
                总价：<span style={{ color: 'rgb(229, 67, 70)' }}>￥{sumPrice}</span>
              </Col>
              <Col span={2}></Col>
            </List.Item>
          )}
        />
      </AxCard>
      <AxCard style={{ margin: '15px auto', width: 1390 }} bodyStyle={{ padding: 0 }}>
        <Row>
          <Col span={16}>
            <Row>
              <Col span={12}>
                <AxSelectEnum
                  form={form}
                  label="付款方式"
                  field="paymentType"
                  enumName="paymentType"
                  required
                />
              </Col>
              <Col span={12}>
                <AxPlaceHolder />
              </Col>
              <Col span={12}>
                <AxInput form={form} label="收货人" field="receiver" required />
              </Col>
              <Col span={12}>
                <AxPlaceHolder />
              </Col>
              <Col span={12}>
                <AxInput
                  form={form}
                  label="联系电话"
                  field="mobile"
                  pattern={axconst.valid.mobile}
                  required
                />
              </Col>
              <Col span={12}>
                <AxPlaceHolder />
              </Col>
              <Col span={12}>
                <AxTextArea form={form} label="收货地址" field="address" required />
              </Col>
              <Col span={12}>
                <AxPlaceHolder />
              </Col>
              {/* <Col span={12}>
                <AxUploadPicture
                  form={form}
                  label="商品图片"
                  field="picPath"
                  uploadUrl={`${databasePrefix}/file/upload`}
                />
              </Col> */}
            </Row>
          </Col>
        </Row>
      </AxCard>
      <AxCard
        style={{ height: '100%', width: 1390, margin: '0 auto' }}
        bodyStyle={{ paddingLeft: 0, paddingRight: 0 }}
      >
        <List
          size="small"
          rowKey={(r: any) => r.id}
          dataSource={[{ id: 'ax-00001' }]}
          renderItem={() => (
            <List.Item>
              <Col span={7}></Col>
              <Col span={3}></Col>
              <Col span={3}></Col>
              <Col span={3}></Col>
              <Col span={2}></Col>
              <Col span={2}></Col>
              <Col span={2}>
                <AxButton className="ax-no-class" onClick={handleSubmit} loading={submiting}>
                  提交订单
                </AxButton>
              </Col>
            </List.Item>
          )}
        />
      </AxCard>
    </>
  );
};

export default Form.create()(Index);
